#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$
import logging
from aggmon.aggregator import Aggregator, AggregatorComponent
from basic_types.metric import Metric


class HostMaxAggregator(Aggregator):
    """
    Provides running maximum of a particular metric. The metric will still 'belong'
    to the same host and will have the maximum value seen for that host since the
    aggregator was started.
    """
    def __init__( self, metric_name, agg_metric_name, group_path="/", **kwds ):
        self.__group_topic = ".".join( group_path.split("/")[1:] )
        # match any host and any data source 
        topic = self.__group_topic + ( len(self.__group_topic) > 0 and "." or "" ) + "*.*." + metric_name
        Aggregator.__init__( self, topic=topic, **kwds )
        self.metric_name = metric_name
        self.agg_metric_name = agg_metric_name
        self.maximum_value = None

    def handleEvent( self, metric, topic=None ):
        #print "max_val aggregator received event:", metric
        if isinstance( metric, Metric ):
            value = metric.value
            if not isinstance( value, ( int, long, float ) ):
                return
            if (self.maximum_value is not None and value > self.maximum_value) \
                or self.maximum_value is None:
                self.maximum_value = value
                topic = "aggregator." + self.agg_metric_name
                params = { "name": self.agg_metric_name,
                           "value": self.maximum_value,
                           "source": "aggregator",
                           "time":  metric.time }
                if hasattr( metric, "host" ):
                    params["host"] = metric.host
                    topic = self.__group_topic + ( len(self.__group_topic) > 0 and "." or "" ) \
                            + metric.host + "." + topic
                max_metric = Metric( **params )
                
                self.publish( topic, max_metric )


class HostMaxAggregatorComponent(AggregatorComponent):
    def instantiate( self, *args, **kwds ):
        self.instance = None
        try:
            logging.debug( "instantiating: %s" % self.name )
            self.instance = HostMaxAggregator( *args, **kwds )
        except Exception, e:
            raise e
